import { makeAutoObservable, runInAction } from 'mobx';
import { RefObject } from 'react';
import { callAIChat, getAgentInfo } from '@/apis/public/chat';
import { Agent_Document_Proofread } from '@/globals/agent';
import { UUID } from '@/utils/uuid';
import { ErrorData } from '@/pages/front/document/documentType';

// 修改为导出类而不是实例
export class ProofreadStore {

    curSessionId: string = '';
    curAgentId: string = Agent_Document_Proofread;
    errorDatas: ErrorData[] = [];
    errorCountData = {
        all: 0,
        accept: 0,
        ignore: 0,
    };

    loading = false;

    constructor() {
        makeAutoObservable(this);

        // 初始化时获取所有agent信息
        this.initAgent();
    }

    /**
     * 初始化agent
     * @param agentId 
     */
    async initAgent() {
        try {
            getAgentInfo({ agentId: this.curAgentId }).then(res => runInAction(() => {
                if (res.status && res.code == 200) {
                    const { sessionId, agentConfig } = res.data;
                    console.log('sessionId', sessionId);
                    this.curSessionId = sessionId;
                }
            }))
        } catch (error) {
        }
    }

    /**
     * 开始校对
     * @param content 
     */
    async documentProofread(content: string) {
        this.loading = true;
        try {
            const params = {
                userId: window.HubUser.id,
                sessionId: this.curSessionId,
                userMessage: content,
                agentId: this.curAgentId,
                additionalParams: {},
            };
            await callAIChat(params).then(res => runInAction(() => {
                if (res.status && res.code == 200) {
                    const { message } = res.data;
                    const proofreadResult = message?.replace(/^[\\n\n]+/, '');
                    const jsonString = proofreadResult.replaceAll('```', '').replace('json\n', '');
                    const _errorDatas = JSON.parse(jsonString);
                    const countMap: Record<string, number> = {};
                    this.errorDatas = _errorDatas.map(
                        item => { 
                            const type = item.errorLevel || 'unknown';
                            countMap[type] = (countMap[type] || 0) + 1;
                            return { id: UUID(), ...item } 
                        }
                    );
                    this.errorCountData = {
                        all: this.errorDatas.length,
                        accept: 0,
                        ignore: 0,
                        ...countMap,
                    };
                    console.log('errorCountData', this.errorCountData);
                    console.log('message', message);
                    console.log('errorData', _errorDatas);
                }
            }));
        } finally {
            this.loading = false;
        }
    }

    /**
     * 接受错误
     * @param item 
     */
    acceptError(item: ErrorData) {
        const idx = this.errorDatas.findIndex(e => e.id === item.id);
        if (idx !== -1) {
            this.errorDatas[idx].isAccept = true;
            const type = item.errorLevel || 'unknown';
            if (this.errorCountData[type] && this.errorCountData[type] > 0) {
                this.errorCountData[type] -= 1;
            }
            this.errorCountData.accept += 1;
        }
    }

    /**
     * 忽略错误
     * @param item 
     */
    ignoreError(item: ErrorData) {
        const idx = this.errorDatas.findIndex(e => e.id === item.id);
        if (idx !== -1) {
            this.errorDatas[idx].isIgnore = true;
            const type = item.errorLevel || 'unknown';
            if (this.errorCountData[type] && this.errorCountData[type] > 0) {
                this.errorCountData[type] -= 1;
            }
            this.errorCountData.ignore += 1;
        }
    }

    /**
     * 全部接受
     */
    acceptAllError() {
        this.errorDatas.forEach(e => {
            this.acceptError(e);
        });
    }   
} 